package com.yh.util;
import org.springframework.util.Base64Utils;
import org.springframework.util.StringUtils;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;

public class AESUtil {
    /**
     * 加密
     * @param content 加密内容
     * @param aesKey 加密aeskey
     * @return
     * @throws Exception
     */
    public static String encryption(String content, String aesKey) throws Exception {
        SecretKeySpec secretKey = new SecretKeySpec(aesKey.getBytes(), "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);

        byte[] bytes = cipher.doFinal(content.getBytes(StandardCharsets.UTF_8));
        return Base64Utils.encodeToString(bytes);
    }

    /**
     * 解密
     * @param content 解密内容
     * @param aesKey 加密使用的key
     * @return
     * @throws Exception
     */
    public static String decrypt(String content, String aesKey) throws Exception{
        byte[] bytes = StringUtils.isEmpty(content) ? null : Base64Utils.decodeFromString(content);
        SecretKeySpec secretKey = new SecretKeySpec(aesKey.getBytes(), "AES");
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        byte[] decryptBytes = cipher.doFinal(bytes);
        return new String(decryptBytes, StandardCharsets.UTF_8);
    }
}
